﻿using System;
using System.IO;
using Microsoft.Office.Interop.Excel;

namespace eCRAM.Tools
{
    public static class ExcelToPdf
    {
        /// <summary>
        /// Sauvegarde le fichier en PDF en utilisant le convertisseur intégré d'Excel
        /// </summary>
        /// <param name="excelFile"></param>
        /// <param name="pdfFile"></param>
        public static void ConvertToPdf(string excelFile, string pdfFile)
        {
            if(!File.Exists(excelFile))
            {
                throw new ArgumentException("Le fichier Excel demandé n'existe pas.");
            }

          
            object paramMissing = System.Reflection.Missing.Value;

            Application excelApplication = new ApplicationClass();
            Workbook excelWorkBook = null;
            try
            {
                //excelWorkBook = excelApplication.Workbooks.Open(excelFile, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                excelWorkBook = excelApplication.Workbooks.Open(excelFile, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing);

                // Save it in the target format.
                if (excelWorkBook != null)
                {
                    excelWorkBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF,
                                                      pdfFile, XlFixedFormatQuality.xlQualityStandard,
                                                      true, true, paramMissing, paramMissing,// 1, 1, // on n'imprime que le 1er onglet
                                                      paramMissing);
                }
            }
            finally
            {
                // Close the workbook object.
                if (excelWorkBook != null)
                {
                    excelWorkBook.Close(false, paramMissing, paramMissing);
                }

                // Quit Excel and release the ApplicationClass object.
                excelApplication.Quit();
                excelApplication = null;

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
    }
}
